﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Fayshine.VA.Helpers;
using Fayshine.VA.Models;
using Fayshine.VA.RIAService.Web;
using Fayshine.VA.ViewModels;
using Visifire.Charts;
using LocalBusyIndicator = Fayshine.VA.Controls.BusyIndicator;

namespace Fayshine.VA.Views.SearchStatistics
{
    public partial class AnyDurationPassengerStatistic : Page
    {
        private SearchStatisticsViewModel m_ViewModel;

        public AnyDurationPassengerStatistic()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(AnyDurationPassengerStatistic_Loaded);
        }

        #region Event Methods

        private void AnyDurationPassengerStatistic_Loaded(object sender, RoutedEventArgs e)
        {
            LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
            indicator.IsBusy = true;

            this.startDatePicker.SelectedDate = DateTime.Now;
            this.endDatePicker.SelectedDate = DateTime.Now;

            m_ViewModel = new SearchStatisticsViewModel();
            m_ViewModel.ResetHisotryChartEvent += new ResetHistoryChartEventHandler(m_ViewModel_ResetHisotryChartEvent);
            m_ViewModel.AppendHistoryPassengerFlow += new AppendHistoryPassengerFlowEventHandler(m_ViewModel_AppendHistoryPassengerFlow);
            this.DataContext = m_ViewModel;

            m_ViewModel.GetAllAreas();
        }

        private void m_ViewModel_AppendHistoryPassengerFlow(string title, bool isIn, List<HistoryPassengerFlow> firstHistoryPassengerFlow, 
                                                            List<HistoryPassengerFlow> secondHistoryPassengerFlow)
        {
           this.Dispatcher.BeginInvoke(delegate()
           {
               string title1 = title;
               Axis xAxis = new Axis();
               DateTime minDateTime = firstHistoryPassengerFlow.Select(s => s.HistoryTime).Min();
               DateTime maxDateTime = firstHistoryPassengerFlow.Select(s => s.HistoryTime).Max();
               xAxis.AxisMinimum = minDateTime;
               xAxis.AxisMaximum = maxDateTime;
               if (maxDateTime.Year == minDateTime.Year && maxDateTime.Month == minDateTime.Month &&
                   maxDateTime.Day == minDateTime.Day)
               {
                   xAxis.ValueFormatString = "HH:mm";
                   xAxis.IntervalType = IntervalTypes.Hours;
                   xAxis.Interval = 1;
               }
               else
               {
                   xAxis.IntervalType = IntervalTypes.Hours;
                   xAxis.Interval = 4;
               }
               vcChart1.AxesX.Add(xAxis);

               int max = 0;
               double avg = 0;
               string path = isIn ? "InCount" : "OutCount";
               string seriesTitle = "进";
               if (isIn)
               {
                   seriesTitle = "进";
                   title1 = string.Format(title, "进客流分布图");
                   max = firstHistoryPassengerFlow.Select(s => s.InCount).Max();
                   avg = firstHistoryPassengerFlow.Select(s => s.InCount).Average();
               }
               else
               {
                   seriesTitle = "出";
                   title1 = string.Format(title, "出客流分布图");
                   max = firstHistoryPassengerFlow.Select(s => s.OutCount).Max();
                   avg = firstHistoryPassengerFlow.Select(s => s.OutCount).Average();
               }

               Title vcChart1Title = new Visifire.Charts.Title();
               vcChart1Title.Text = title1;
               vcChart1.Titles.Add(vcChart1Title);

               TrendLine maxLine = new TrendLine();
               maxLine.Value = max;
               maxLine.LabelText = "最大:" + max.ToString();
               maxLine.FlowDirection = System.Windows.FlowDirection.LeftToRight;
               maxLine.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
               
               TrendLine avgLine = new TrendLine();
               avgLine.Value = avg;
               avgLine.LabelText = "平均:" + Convert.ToInt32(avg).ToString();
               avgLine.FlowDirection = System.Windows.FlowDirection.LeftToRight;
               vcChart1.TrendLines.Add(maxLine);
               vcChart1.TrendLines.Add(avgLine);

               DataSeries series = ChartHelper.GetDataSeries(RenderAs.Line, seriesTitle, ChartValueTypes.DateTime);
               series.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
               series.DataMappings.Add(ChartHelper.GetDataMapping("YValue", path));
               series.DataSource = firstHistoryPassengerFlow;
               vcChart1.Series.Add(series);

               string title2 = string.Format(title, "滞留人数分布图");
               Title vcChart2Title = new Visifire.Charts.Title();
               vcChart2Title.Text = title2;
               vcChart2.Titles.Add(vcChart2Title);
               vcChart2.AxesX.Add(xAxis);
               DataSeries accInSeries = ChartHelper.GetDataSeries(RenderAs.Area, "累计进", ChartValueTypes.DateTime);
               accInSeries.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
               accInSeries.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "AccumulateInCount"));
               accInSeries.DataSource = firstHistoryPassengerFlow;

               DataSeries accOutSeries = ChartHelper.GetDataSeries(RenderAs.Area, "累计出", ChartValueTypes.DateTime);
               accOutSeries.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
               accOutSeries.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "AccumulateOutCount"));
               accOutSeries.DataSource = firstHistoryPassengerFlow;

               DataSeries strandedSeries = ChartHelper.GetDataSeries(RenderAs.Area, "滞留人数", ChartValueTypes.DateTime);
               strandedSeries.DataMappings.Add(ChartHelper.GetDataMapping("XValue", "HistoryTime"));
               strandedSeries.DataMappings.Add(ChartHelper.GetDataMapping("YValue", "StrandedCount"));
               strandedSeries.DataSource = firstHistoryPassengerFlow;
               vcChart2.Series.Add(accInSeries);
               vcChart2.Series.Add(accOutSeries);
               vcChart2.Series.Add(strandedSeries);

               this.dataGrid.ItemsSource = firstHistoryPassengerFlow;

               LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
               indicator.IsBusy = false;
           
           });
        }

        private void m_ViewModel_ResetHisotryChartEvent()
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                if (vcChart1 != null)
                {
                    vcChart1.AxesX.Clear();
                    vcChart1.TrendLines.Clear();
                    vcChart1.Series.Clear();
                    vcChart1.Titles.Clear();
                }

                if (vcChart2 != null)
                {
                    vcChart2.AxesX.Clear();
                    vcChart2.TrendLines.Clear();
                    vcChart2.Series.Clear();
                    vcChart2.Titles.Clear();
                }
            });
        }

        private void cmbAreas_DropDownOpened(object sender, EventArgs e)
        {

        }

        private void cmbAreas_DropDownClosed(object sender, EventArgs e)
        {
            if (m_ViewModel != null)
            {
                List<area> selectedArea = new List<area>();
                var selectAreaExt = m_ViewModel.AreaExtends.Where(a => a.IsSelected).ToList();
                selectAreaExt.ForEach(b =>
                {
                    area temp = b.Tag as area;
                    selectedArea.Add(temp);
                });

                if (selectedArea.Count > 0)
                {
                    cbItemDisplay.Content = selectedArea.Count > 1 ? selectedArea[0].Name + "..." : selectedArea[0].Name;

                    if (selectedArea.Count > 1)
                    {
                        this.cmbPassenger.IsEnabled = false;
                    }
                    else
                    {
                        this.cmbPassenger.IsEnabled = true;
                    }

                }
                else
                {
                    cbItemDisplay.Content = string.Empty;
                }
                cmbAreas.SelectedItem = null;
                cmbAreas.SelectedItem = cbItemDisplay;

                m_ViewModel.SelectAreasChanged(selectedArea);
                cmbPassenger_DropDownClosed(null, null);
            }
        }

        private void cmbPassenger_DropDownOpened(object sender, EventArgs e)
        {
        }

        private void cmbPassenger_DropDownClosed(object sender, EventArgs e)
        {
            if (m_ViewModel != null)
            {
                var selectMonitorAreaExts = m_ViewModel.MonitorAreaGateExts.Where(a => a.IsSelected).ToList();

                if (selectMonitorAreaExts.Count > 0)
                {
                    cbItemDisplay2.Content = selectMonitorAreaExts.Count > 1 ? selectMonitorAreaExts[0].Name + "..." : selectMonitorAreaExts[0].Name;

                }
                else
                {
                    cbItemDisplay2.Content = string.Empty;
                }
                cmbPassenger.SelectedItem = null;
                cmbPassenger.SelectedItem = cbItemDisplay2;
            }
        }

        #endregion

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            if (!m_ViewModel.IsConditionSelected())
            {
                MessageBox.Show("请选择店铺或者门面！");
                return;
            }
            DateTime startTime = new DateTime(startDatePicker.SelectedDate.Value.Year,
                                              startDatePicker.SelectedDate.Value.Month,
                                              startDatePicker.SelectedDate.Value.Day,
                                              0, 0, 0);
            DateTime endTime = new DateTime(endDatePicker.SelectedDate.Value.Year,
                                            endDatePicker.SelectedDate.Value.Month,
                                            endDatePicker.SelectedDate.Value.Day,
                                            23, 59, 59);

            if (endTime < startTime)
            {
                MessageBox.Show("开始时间不能大于结束时间");
            }
            else
            {
                LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                indicator.IsBusy = true;
                bool isIn = cmbInorOut.SelectedIndex == 0 ? true : false;
                m_ViewModel.RefreshAnyDurationPassengerStatistic(isIn, startTime, endTime);
            }
        }

        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog fsd = new SaveFileDialog();
            fsd.Filter = "PDF (*.pdf)|*.pdf|*PNG (*.png)|*.png";

            if (fsd.ShowDialog() == true)
            {
                LocalBusyIndicator indicator = Application.Current.RootVisual as LocalBusyIndicator;
                indicator.IsBusy = true;
                this.Dispatcher.BeginInvoke(delegate()
                {
                    FayshineManager.Instance.ExportToDisk(fsd, spContent);
                });
            }
        }

    }
}
